#include "convert_thread.h"

Convert_Thread::Convert_Thread(const QStringList& srcFileName,const QString& filename,QTextCodec* srcCodec,QTextCodec* finalCodec)
{
    m_threadFileName = srcFileName ;
    sFileName = filename ;
    m_pSourceCodec = srcCodec ;
    m_pFinalCodec  = finalCodec ;
}

void Convert_Thread::run()
{

    if(m_threadFileName.size()==0)
    {
        terminate();
        wait() ;
    }
    for(int i = 0 ;i!=m_threadFileName.size();i++)
    {
        QFile SourceFile, FinallyFile ;
        QTextStream read,write ;
//read
        QString sSrcfile = m_threadFileName[i] ;
        sSrcfile.replace("/",QDir::separator()) ;
        if(sSrcfile.endsWith(".cpp")||sSrcfile.endsWith(".h")||sSrcfile.endsWith(".txt")||sSrcfile.endsWith(".wks"))
        {
            SourceFile.setFileName(m_threadFileName[i]);

            if(!SourceFile.open(QFile::ReadOnly|QFile::Text))
            {
                terminate();
                wait() ;
                return;
            }

            read.setDevice(&SourceFile) ;
            read.setAutoDetectUnicode(false) ;
            read.setCodec(m_pSourceCodec);
            QString sTemp ;
            sTemp = read.readAll() ;

//convert
            QString sFinalFile ;
            QFileInfo fileInfo(m_threadFileName[i]) ;
            sFinalFile =sFileName+QDir::separator()+ fileInfo.fileName() ;


            FinallyFile.setFileName(sFinalFile) ;
            if(!FinallyFile.open(QFile::WriteOnly|QFile::Text))
            {
                terminate();
                wait() ;
                return;
            }

            write.setDevice(&FinallyFile) ;
            write.setCodec(m_pFinalCodec) ;
            write << sTemp ;

            SourceFile.close()  ;
            FinallyFile.close() ;
        }

    }
}
